﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.Geodatabase;

namespace ODM_Code.Forms
{
    public partial class AddOptFuelsDataForm2 : Form
    {
        private string dbfPath = "C:\\magfire\\" + ConfigSettings.ReadSetting("analysisArea");
        private string inputPath = "C:\\magfire\\" + ConfigSettings.ReadSetting("analysisArea") + "\\input";
        private ODM_Code.rUtils ru;
        private esriUtil.rasterUtil eru;

        private IMap map;
        private IActiveView view;

        private Boolean preSelectBool = false;

        public AddOptFuelsDataForm2()
        {
            InitializeComponent();
            //ru = new ODM_Code.rUtils();
        }

        public AddOptFuelsDataForm2(IMxDocument pMxDoc)
        {
            InitializeComponent();
            ru = new ODM_Code.rUtils();
            eru = new esriUtil.rasterUtil();
            IMxDocument doc = pMxDoc;
            map = doc.FocusMap;
            view = doc.ActiveView;

            map.SpatialReference = ru.GetAlbersProjection();

            preSelectBool = true;
        }

        public AddOptFuelsDataForm2(IMxDocument pMxDoc, string preSelectAlternative)
        {
            InitializeComponent();
            ru = new ODM_Code.rUtils();
            eru = new esriUtil.rasterUtil();
            IMxDocument doc = pMxDoc;
            map = doc.FocusMap;
            view = doc.ActiveView;

            map.SpatialReference = ru.GetAlbersProjection();

            preSelectBool = true;
        }

        private void AddOptFuelsDataForm_Load(object sender, EventArgs e)
        {
            
            string[] files = System.IO.Directory.GetDirectories(inputPath);
            foreach (string s in files)
            {
                string[] spl = s.Split('\\');
                int i = spl.Length;

                string addThis = spl[i - 1];
                if (addThis.StartsWith("S"))
                {
                    this.comboBox1.Items.Add(addThis);
                }
            }

            if (preSelectBool == true)
            {
                this.comboBox1.SelectedText = ConfigSettings.ReadSetting("currentAlternative");
                this.setCheckboxes();
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.setCheckboxes();
        }

        private void checkNA_CheckedChanged(object sender, EventArgs e)
        {
            if (checkNA.Checked)
            {
                checkNaAt.Checked = true;
                checkNaBp.Checked = true;
                checkNaEl.Checked = true;
                checkNaNf.Checked = true;
            }
            else
            {
                checkNaAt.Checked = false;
                checkNaBp.Checked = false;
                checkNaEl.Checked = false;
                checkNaNf.Checked = false;
 
            }
        }

        private void checkTr_CheckedChanged(object sender, EventArgs e)
        {
            if (checkTr.Checked)
            {
                checkTrAt.Checked = true;
                checkTrBp.Checked = true;
                checkTrEl.Checked = true;
                checkTrNf.Checked = true;
                treatSchedBox.Checked = true;
            }
            else
            {
                checkTrAt.Checked = false;
                checkTrBp.Checked = false;
                checkTrEl.Checked = false;
                checkTrNf.Checked = false;
                treatSchedBox.Checked = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Set up base paths and filenames
            string resultsPath = inputPath + "\\" + comboBox1.Text + "\\results";
            string gisPath = inputPath + "\\" + comboBox1.Text + "\\results\\gis\\";
            string dllPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string hollowPath = dllPath + "\\res\\AnalysisAreasHollow.lpk";

            if (!Directory.Exists(gisPath))
            {
                Directory.CreateDirectory(gisPath);
            }

            // Start with user input checks
            // First, alternative is selected
            // Second, at least one fire checked
            // Third, at least on period checked
            // Last, a valid solution iteration has been entered/found

            if (comboBox1.Text.Equals(""))
            {
                MessageBox.Show("You must select an alternative.", "Alternative not selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (this.checkUserInputFires() == false)
            {
                MessageBox.Show("You must select at least 1 fire.", "Fire not selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (this.checkUserInputPeriods() == false)
            {
                MessageBox.Show("You must select at least 1 period.", "Period not selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int bestSol = 0;
            if (iterationBox.Text.Equals(""))
            {
                try
                {
                    bestSol = ru.GetBestSolutionNum(resultsPath);
                    MessageBox.Show("Using iteration " + bestSol.ToString(), "Best Treatment Found!");
                }
                catch (FileLoadException flex)
                {
                    System.Diagnostics.Trace.WriteLine(flex.Message);
                    return;
                }
            }
            else
            {
                bestSol = int.Parse(iterationBox.Text);
                if (ru.CheckIteration(resultsPath, bestSol) == false)
                {
                    MessageBox.Show("Invalid iteration chosen. Please enter a valid iteration to load.", "Iteration File Load Error");
                    return;
                }
                else
                {
                    MessageBox.Show("Using iteration " + bestSol.ToString(), "User-entered Iteration");
                }
            }

            

            // Check if the "Clear Map" checkbox has been checked, and clear the map if so.
            if (chkClearMap.Checked)
            {
                map.ClearLayers();
                view.Refresh();
                view.ContentsChanged();
            }

            try
            {
                if (chkRebuildGis.Checked)
                {
                    this.nukeOldGisFiles(gisPath);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("NukeOldFiles Error\n" + ex.Message + "\n\nFiles will not be rewritten.", "NukeOldFiles Error");
                System.Diagnostics.Trace.WriteLine(ex.Message, "NukeOldFiles");
            }
           

            #region strings
            string selectedFile = "";
            string inputFile = "";
            string layerRender = "";
            string period = "1";
            string fireNum = "1";
            //string baseFl = "flamelength";
            string baseFl = "nodeflamelength";
            string baseBp = "burnprobability";
            string baseAt = "arrivaltime";
            string baseEl = "objvalues";
            string baseTrPer = "treatPeriod";
            string baseTrReg = "treatRegime";
           
            string layerFl = "nodeFlame.lyr";
            string layerBp = "burnProb.lyr";
            string layerAt = "arrivalTime.lyr";
            string layerEl = "expectedLoss.lyr";
            string layerTrPer = "treatPeriod.lyr";
            string layerTrReg = "tr_regime.lyr";

            string rasName = "";
            #endregion

            ODM_Code.Forms.ProgressForm pf = new ODM_Code.Forms.ProgressForm(1, this.countChecks(), 1);
            pf.Show();
            pf.Activate();
            pf.BringToFront();
            pf.SetProgressLabel("Adding layers to map.");

            IRaster ras = null;  // IRaster temp holder for new rasters
            IRasterLayer rasLayer = null;  // IRasterLayer holder for adding to map
            ILegendInfo lInfo = null;  // ILegendInfo holder

            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
            IWorkspace wks = (IWorkspace)(workspaceFactory.OpenFromFile(gisPath, 0));
            string saveExtention = ".tif";

            List<CheckBox> fireBoxes = new List<CheckBox>{ fire1CheckBox, fire2CheckBox, fire3CheckBox, fire4CheckBox };
            List<CheckBox> periodBoxes = new List<CheckBox> { period1CheckBox, period2CheckBox, period3CheckBox, period4CheckBox };
            List<CheckBox> noactionBoxes = new List<CheckBox> { checkNaAt, checkNaBp, checkNaEl, checkNaNf };
            List<CheckBox> treatmentBoxes = new List<CheckBox> { checkTrAt, checkTrBp, checkTrEl, checkTrNf };

            int fireLoopCount = 0;
            foreach (CheckBox fireBox in fireBoxes)
            {
                if (!fireBox.Checked)
                {
                    continue;
                }

                fireLoopCount += 1;

                switch (fireBox.Text)
                {
                    case "1":
                        fireNum = "1";
                        break;
                    case "2":
                        fireNum = "2";
                        break;
                    case "3":
                        fireNum = "3";
                        break;
                    case "4":
                        fireNum = "4";
                        break;
                }

                IGroupLayer fireGroup = this.getFireGroup(comboBox1.Text + " Fire " + fireNum);
                IGroupLayer naGroup = this.getNoActionGroup(fireGroup);
                IGroupLayer trGroup = this.getTreatmentGroup(fireGroup, "Treatment (" + bestSol.ToString() + ")");
                                
                foreach (CheckBox perBox in periodBoxes)
                {
                    if (!perBox.Checked)
                    {
                        continue;
                    }

                    switch (perBox.Text)
                    {
                        case "1":
                            period = "1";
                            break;
                        case "2":
                            period = "2";
                            break;
                        case "3":
                            period = "3";
                            break;
                        case "4":
                            period = "4";
                            break;
                    }

                    foreach (CheckBox naBox in noactionBoxes)
                    {
                        try
                        {
                            if (!naBox.Checked)
                            {
                                continue;
                            }

                            switch (naBox.Text)
                            {
                                case "Arrival Time":
                                    selectedFile = baseAt + "0_" + fireNum + "_" + period + saveExtention;
                                    inputFile = resultsPath + "\\" + baseAt + "0_" + fireNum + "_" + period + ".txt";
                                    pf.SetProgressLabel("Adding " + selectedFile);
                                    rasName = "Arrival Time, Period " + period;
                                    layerRender = layerAt;
                                    break;
                                case "Burn Probability":
                                    selectedFile = baseBp + "0_" + fireNum + "_" + period + saveExtention;
                                    inputFile = resultsPath + "\\" + baseBp + "0_" + fireNum + "_" + period + ".txt";
                                    pf.SetProgressLabel("Adding " + selectedFile);
                                    rasName = "Burn Probability, Period " + period;
                                    layerRender = layerBp;
                                    break;
                                case "Node Flamelength":
                                    selectedFile = baseFl + "0_" + fireNum + "_" + period + saveExtention;
                                    inputFile = resultsPath + "\\" + baseFl + "0_" + fireNum + "_" + period + ".txt";
                                    pf.SetProgressLabel("Adding " + selectedFile);
                                    rasName = "Flame Length, Period " + period;
                                    layerRender = layerFl;
                                    break;
                                case "Expected Loss":
                                    selectedFile = baseEl + "0_" + fireNum + "_" + period + saveExtention;
                                    inputFile = resultsPath + "\\" + baseEl + "0_" + fireNum + "_" + period + ".txt";
                                    pf.SetProgressLabel("Adding " + selectedFile);
                                    rasName = "Expected Loss, Period " + period;
                                    layerRender = layerEl;
                                    break;
                            }

                            if (File.Exists(gisPath + selectedFile))
                            {
                                ras = eru.returnRaster(gisPath + selectedFile);
                                rasLayer = ru.PrepRasterForMap(ras, layerRender, rasName);
                                rasLayer.Visible = false;
                                lInfo = (ILegendInfo)rasLayer;
                                lInfo.get_LegendGroup(0).Visible = false;
                                naGroup.Add(rasLayer);
                            }
                            else
                            {
                                ras = ru.AddDataFormMakeRaster(inputFile, eru);
                                rasLayer = ru.PrepRasterForMap(ras, layerRender, rasName);
                                ru.AddDataFormSaveRaster(ras, selectedFile, wks, saveExtention);
                                rasLayer.Visible = false;
                                lInfo = (ILegendInfo)rasLayer;
                                lInfo.get_LegendGroup(0).Visible = false;
                                naGroup.Add(rasLayer);
                            }

                            pf.StepBar();

                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.WriteLine(ex.Message, "Add NoAction Data");
                            MessageBox.Show(ex.Message, "Add NoAction Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                    foreach (CheckBox trBox in treatmentBoxes)
                    {
                        if (!trBox.Checked)
                        {
                            continue;
                        }
                        try
                        {
                            switch (trBox.Text)
                            {
                                case "Arrival Time":
                                    selectedFile = baseAt + bestSol + "_" + fireNum + "_" + period + saveExtention;
                                    inputFile = resultsPath + "\\" + baseAt + bestSol + "_" + fireNum + "_" + period + ".txt";
                                    pf.SetProgressLabel("Adding " + selectedFile);
                                    rasName = "Arrival Time, Period " + period;
                                    layerRender = layerAt;
                                    break;
                                case "Burn Probability":
                                    selectedFile = baseBp + bestSol + "_" + fireNum + "_" + period + saveExtention;
                                    inputFile = resultsPath + "\\" + baseBp + bestSol + "_" + fireNum + "_" + period + ".txt";
                                    pf.SetProgressLabel("Adding " + selectedFile);
                                    rasName = "Burn Probability, Period " + period;
                                    layerRender = layerBp;
                                    break;
                                case "Node Flamelength":
                                    selectedFile = baseFl + bestSol + "_" + fireNum + "_" + period + saveExtention;
                                    inputFile = resultsPath + "\\" + baseFl + bestSol + "_" + fireNum + "_" + period + ".txt";
                                    pf.SetProgressLabel("Adding " + selectedFile);
                                    rasName = "Flame Length, Period " + period;
                                    layerRender = layerFl;
                                    break;
                                case "Expected Loss":
                                    selectedFile = baseEl + bestSol + "_" + fireNum + "_" + period + saveExtention;
                                    inputFile = resultsPath + "\\" + baseEl + bestSol + "_" + fireNum + "_" + period + ".txt";
                                    pf.SetProgressLabel("Adding " + selectedFile);
                                    rasName = "Expected Loss, Period " + period;
                                    layerRender = layerEl;
                                    break;
                            }

                            if (File.Exists(gisPath + selectedFile))
                            {
                                ras = eru.returnRaster(gisPath + selectedFile);
                                rasLayer = ru.PrepRasterForMap(ras, layerRender, rasName);
                                rasLayer.Visible = false;
                                lInfo = (ILegendInfo)rasLayer;
                                lInfo.get_LegendGroup(0).Visible = false;
                                trGroup.Add(rasLayer);
                            }
                            else
                            {
                                ras = ru.AddDataFormMakeRaster(inputFile, eru);
                                rasLayer = ru.PrepRasterForMap(ras, layerRender, rasName);
                                ru.AddDataFormSaveRaster(ras, selectedFile, wks, saveExtention);
                                rasLayer.Visible = false;
                                lInfo = (ILegendInfo)rasLayer;
                                lInfo.get_LegendGroup(0).Visible = false;
                                trGroup.Add(rasLayer);
                            }

                            pf.StepBar();
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.WriteLine(ex.Message, "Add Treatment Data");
                            MessageBox.Show(ex.Message, "Add Treatment Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                }

                //naGroup.Expanded = false;
                naGroup.Visible = true;
                //trGroup.Expanded = false;
                trGroup.Visible = true;

                fireGroup.Add(naGroup);
                fireGroup.Add(trGroup);
                fireGroup.Visible = true;

                map.AddLayer(fireGroup);
            }
            
            pf.Visible = false;  // Temporarily hide this progress bar

            if (treatSchedBox.Checked)
            {
                try
                {
                    selectedFile = baseTrPer + saveExtention;
                    inputFile = resultsPath + "\\TR_period.txt";

                    rasName = comboBox1.Text + " Treatment Period";

                    if (File.Exists(gisPath + selectedFile))
                    {
                        ras = eru.returnRaster(gisPath + selectedFile);
                        rasLayer = ru.PrepRasterForMap(ras, layerTrPer, rasName);
                        rasLayer.Visible = false;
                        lInfo = (ILegendInfo)rasLayer;
                        lInfo.get_LegendGroup(0).Visible = false;
                        this.checkTreatmentScheduleExisting(rasLayer);
                        map.AddLayer(rasLayer);
                    }
                    else
                    {
                        ru.IntPrjIdLookup(resultsPath, bestSol, true);
                        ras = ru.AddDataFormMakeRaster(inputFile, eru);
                        rasLayer = ru.PrepRasterForMap(ras, layerTrPer, rasName);
                        ru.AddDataFormSaveRaster(ras, selectedFile, wks, saveExtention);
                        rasLayer.Visible = false;
                        lInfo = (ILegendInfo)rasLayer;
                        lInfo.get_LegendGroup(0).Visible = false;
                        this.checkTreatmentScheduleExisting(rasLayer);
                        map.AddLayer(rasLayer);
                    }
                }
                catch (IndexOutOfRangeException ioorEx)
                {
                    MessageBox.Show("Index out of range.\nMake sure the correct 54.dbf is being used.\n\n" + ioorEx.Message, "Exception in Treatment Regime", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                pf.StepBar();

                try
                {
                    selectedFile = baseTrReg + saveExtention;
                    inputFile = resultsPath + "\\TR_regime.txt";
                    
                    rasName = comboBox1.Text + " Treatment Regime";

                    if (File.Exists(gisPath + selectedFile))
                    {
                        ras = eru.returnRaster(gisPath + selectedFile);
                        rasLayer = ru.PrepRasterForMap(ras, layerTrReg, rasName);
                        rasLayer.Visible = false;
                        lInfo = (ILegendInfo)rasLayer;
                        lInfo.get_LegendGroup(0).Visible = false;
                        this.checkTreatmentScheduleExisting(rasLayer);
                        map.AddLayer(rasLayer);
                    }
                    else
                    {
                        ru.IntPrjIdLookup(resultsPath, bestSol, false);
                        ru.GetRegimeValues(dbfPath + "\\_43b.DBF", resultsPath);
                        ras = ru.AddDataFormMakeRaster(inputFile, eru);
                        rasLayer = ru.PrepRasterForMap(ras, layerTrReg, rasName);
                        ru.AddDataFormSaveRaster(ras, selectedFile, wks, saveExtention);
                        rasLayer.Visible = false;
                        lInfo = (ILegendInfo)rasLayer;
                        lInfo.get_LegendGroup(0).Visible = false;
                        this.checkTreatmentScheduleExisting(rasLayer);
                        map.AddLayer(rasLayer);
                    }
                }
                catch (IndexOutOfRangeException ioorEx)
                {
                    MessageBox.Show("Index out of range.\nMake sure the correct 54.dbf is being used.\n\n" + ioorEx.Message, "Exception in Treatment Regime", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                pf.StepBar();
            }

            pf.Visible = true;  // Return visibility to form
            pf.BringToFront();

            pf.SetProgressLabel("Done!");
            pf.Close();

            
            // Normally, this control is hidden and set to 'true', but check anyway and
            // add the ignition shapefile accordingly
            if (chkIgnitionFile.Checked)
            {
                for (int i = 1; i <= int.Parse(fireNum); i++)
                {
                    try
                    {
                        string igPath = ru.GetIgnitionFilePath(comboBox1.Text, i.ToString());
                        this.addIgnitionFileToMap(igPath);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Trace.WriteLine(ex.Message, "AddIgnitionToMap");
                        System.Diagnostics.Trace.WriteLine(ex.InnerException.Message, "AddIgnitionToMap InnerException");
                    }
                }
            }

            // Add the 'hollow' (outline) analysis areas layer for Tahoe areas
            try
            {
                string currScen = ConfigSettings.ReadSetting("analysisArea");
                switch (currScen)
                {
                    case "DBF_LT_NORTH":
                    case "DBF_LT_WEST":
                    case "DBF_LT_EAST":
                    case "DBF_LT_SOUTH":
                    case "DBF_TUT_WEST":
                        this.addHollowFileToMap(hollowPath);
                        break;
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message, "AddHollowLayer");
            }

            view.Refresh();
            view.ContentsChanged();
            MessageBox.Show("Selected data added to map.", "Add OptFuels Data");
            this.Close();
        }

        private void addHollowFileToMap(String layerFilePath)
        {
            bool add = true;
            for (int i = 0; i < map.LayerCount; i++)
            {
                string name = map.get_Layer(i).Name;
                if (name.Equals("Analysis Areas"))
                {
                    add = false;
                }
            }

            if (add)
            {
                ILayerFile lFile = new LayerFileClass();
                lFile.Open(layerFilePath);
                ILayer layer = lFile.Layer;

                ILegendInfo lInfo = (ILegendInfo)layer;
                lInfo.get_LegendGroup(0).Visible = false;

                if (layer != null)
                {
                    map.AddLayer(layer);
                }
            }
        }

        private void addIgnitionFileToMap(String ignitionPath)
        {
            int startInd = ignitionPath.LastIndexOf("\\") + 1;
            int endInd = ignitionPath.LastIndexOf(".");
            string ignitionName = ignitionPath.Substring(startInd, (endInd - startInd));
            ignitionName = ignitionName.ToLower();
            bool add = true;
            for (int i = 0; i < map.LayerCount; i++)
            {
                string name = map.get_Layer(i).Name;
                if (name.Equals(ignitionName))
                {
                    add = false;
                }
            }

            if (add)
            {
                ru.AddShapefileToMap(view, ignitionPath);
            }
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            //AddDataHelpForm adhf = new AddDataHelpForm();
            //adhf.ShowDialog();
            //adhf.Activate();
            //adhf.BringToFront();

            MessageBox.Show("Help system under development. Please refer to included documentation", "Not Implemented Yet");
        }

        private bool checkUserInputFires()
        {
            int fireBoxCount = 0;
            
            foreach (Control c in fireBox.Controls)
            {
                if (c is CheckBox)
                {
                    CheckBox cb = (CheckBox)c;
                    if (cb.Checked)
                    {
                        fireBoxCount += 1;
                    }
                }
            }

            if (fireBoxCount == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool checkUserInputPeriods()
        {
            int periodBoxCount = 0;

            foreach (Control c in periodBox.Controls)
            {
                if (c is CheckBox)
                {
                    CheckBox cb = (CheckBox)c;
                    if (cb.Checked)
                    {
                        periodBoxCount += 1;
                    }
                }
            }

            if (periodBoxCount == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private int countChecks()
        {
            int fireBoxCount = 0;
            int periodBoxCount = 0;
            int count = 0;

            foreach (Control c in fireBox.Controls)
            {
                if (c is CheckBox)
                {
                    CheckBox cb = (CheckBox)c;
                    if (cb.Checked)
                    {
                        fireBoxCount += 1;
                    }
                }
            }

            foreach (Control c in periodBox.Controls)
            {
                if (c is CheckBox)
                {
                    CheckBox cb = (CheckBox)c;
                    if (cb.Checked)
                    {
                        periodBoxCount += 1;
                    }
                }
            }

            if (checkNaAt.Checked) { count += 1; }
            if (checkNaBp.Checked) { count += 1; }
            if (checkNaEl.Checked) { count += 1; }
            if (checkNaNf.Checked) { count += 1; }
            if (checkTrAt.Checked) { count += 1; }
            if (checkTrBp.Checked) { count += 1; }
            if (checkTrEl.Checked) { count += 1; }
            if (checkTrNf.Checked) { count += 1; }

            count = count * periodBoxCount * fireBoxCount;

            if (treatSchedBox.Checked) { count += 2; }

            return count;
        }

        private IGroupLayer getFireGroup(string newGroupName)
        {
            for (int i = 0; i < map.LayerCount; i++)
            {
                ILayer pLayer = map.get_Layer(i);
                if (pLayer is GroupLayerClass)
                {
                    if (pLayer.Name.Equals(newGroupName))
                    {
                        map.DeleteLayer(pLayer);
                        return (IGroupLayer)pLayer;
                    }
                }
            }

            IGroupLayer newGroupLayer = new GroupLayerClass();
            newGroupLayer.Name = newGroupName;
            return newGroupLayer;
        }

        private IGroupLayer getNoActionGroup(IGroupLayer fireGroupLayer)
        {
            ICompositeLayer compFireLayer = (ICompositeLayer)fireGroupLayer;
            if (compFireLayer.Count > 0)
            {
                for (int i = 0; i < compFireLayer.Count; i++)
                {
                    ILayer pLayer = compFireLayer.get_Layer(i);
                    if (pLayer.Name.Equals("No Action"))
                    {
                        map.DeleteLayer(pLayer);
                        return (IGroupLayer)pLayer;
                    }
                }
            }

            IGroupLayer noActionGroup = new GroupLayerClass();
            noActionGroup.Name = "No Action";
            return noActionGroup;
        }

        private IGroupLayer getTreatmentGroup(IGroupLayer fireGroupLayer, string treatmentName)
        {
            ICompositeLayer compFireLayer = (ICompositeLayer)fireGroupLayer;
            if (compFireLayer.Count > 0)
            {
                for (int i = 0; i < compFireLayer.Count; i++)
                {
                    ILayer pLayer = compFireLayer.get_Layer(i);
                    if (pLayer.Name.Equals(treatmentName))
                    {
                        map.DeleteLayer(pLayer);
                        return (IGroupLayer)pLayer;
                    }
                }
            }

            IGroupLayer treatmentGroup = new GroupLayerClass();
            treatmentGroup.Name = treatmentName;
            return treatmentGroup;
        }

        private void checkTreatmentScheduleExisting(ILayer checkLayer)
        {
            for (int i = 0; i < map.LayerCount; i++)
            {
                if (map.get_Layer(i).Name.Equals(checkLayer.Name))
                {
                    map.DeleteLayer(map.get_Layer(i));
                }
            }
        }

        private void setCheckboxes()
        {
            string resultsPath = inputPath + "\\" + comboBox1.Text + "\\results";
            try
            {
                int fireCount = ru.CheckMultifireBounds(resultsPath);
                int periodCount = ru.CheckPeriodBounds(resultsPath);

                switch (fireCount)
                {
                    case 1:
                        fire1CheckBox.Enabled = true;
                        fire2CheckBox.Enabled = false;
                        fire3CheckBox.Enabled = false;
                        fire4CheckBox.Enabled = false;
                        break;
                    case 2:
                        fire1CheckBox.Enabled = true;
                        fire2CheckBox.Enabled = true;
                        fire3CheckBox.Enabled = false;
                        fire4CheckBox.Enabled = false;
                        break;
                    case 3:
                        fire1CheckBox.Enabled = true;
                        fire2CheckBox.Enabled = true;
                        fire3CheckBox.Enabled = true;
                        fire4CheckBox.Enabled = false;
                        break;
                    case 4:
                        fire1CheckBox.Enabled = true;
                        fire2CheckBox.Enabled = true;
                        fire3CheckBox.Enabled = true;
                        fire4CheckBox.Enabled = true;
                        break;
                }
                switch (periodCount)
                {
                    case 1:
                        period1CheckBox.Enabled = true;
                        period2CheckBox.Enabled = false;
                        period3CheckBox.Enabled = false;
                        period4CheckBox.Enabled = false;
                        break;
                    case 2:
                        period1CheckBox.Enabled = true;
                        period2CheckBox.Enabled = true;
                        period3CheckBox.Enabled = false;
                        period4CheckBox.Enabled = false;
                        break;
                    case 3:
                        period1CheckBox.Enabled = true;
                        period2CheckBox.Enabled = true;
                        period3CheckBox.Enabled = true;
                        period4CheckBox.Enabled = false;
                        break;
                    case 4:
                        period1CheckBox.Enabled = true;
                        period2CheckBox.Enabled = true;
                        period3CheckBox.Enabled = true;
                        period4CheckBox.Enabled = true;
                        break;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Bounds Error");
                System.Diagnostics.Trace.WriteLine(ex.Message, "AddOptFuelsDataForm CheckBounds Error");
            }

            this.checkNA.Enabled = true;
            this.checkNaAt.Enabled = true;
            this.checkNaBp.Enabled = true;
            this.checkNaEl.Enabled = true;
            this.checkNaNf.Enabled = true;
            this.checkTr.Enabled = true;
            this.checkTrAt.Enabled = true;
            this.checkTrBp.Enabled = true;
            this.checkTrEl.Enabled = true;
            this.checkTrNf.Enabled = true;
            this.treatSchedBox.Enabled = true;

            bool isZRun = false;

            try
            {
                isZRun = ru.CheckForZRun(comboBox1.Text);
            }
            catch
            {
                return;
            }

            if (comboBox1.Text.Equals("S1_NA"))
            {
                this.checkTr.Enabled = false;
                this.checkTrAt.Enabled = false;
                this.checkTrBp.Enabled = false;
                this.checkTrEl.Enabled = false;
                this.checkTrNf.Enabled = false;
                this.treatSchedBox.Enabled = false;
            }
            if (isZRun && !comboBox1.Text.Equals("S1_NA"))
            {
                this.checkNA.Enabled = false;
                this.checkNaAt.Enabled = false;
                this.checkNaBp.Enabled = false;
                this.checkNaEl.Enabled = false;
                this.checkNaNf.Enabled = false;
            }
        }

        private void nukeOldGisFiles(string gisFolder)
        {
            bool lockPresent = false;
            string[] files = Directory.GetFiles(gisFolder);
            foreach (string f in files)
            {
                if (f.EndsWith("lock"))
                {
                    lockPresent = true;
                }
                File.Delete(f);
            }

            if (lockPresent)
            {
                MessageBox.Show("One or more files in the selected GIS directory appear to be locked,\nlikely because they are in use by another program. Rebuilding layers\nmay not work correctly.", "Warning: File Locks Present");
            }
        }
    }
}
